/*
 *
 * BirdToast
 *
 *
 *
 * Nate Slottow, 2008
 *
 */

#include "globals.h"

using namespace bt;

Animation *animTest;

/*
 * Initialize SDL and OpenGL window
 */
void InitVideo()
{
	SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER);
	
	g_windowSurface = SDL_SetVideoMode(g_winWidth, g_winHeight, g_winBpp, g_winFlags);
	
	if(!g_windowSurface)
	{
		fprintf(stderr, "Couldn't set video mode: %s\n", SDL_GetError());
		SDL_Quit();
		exit(2);
	}
	
	// Set window options
	SDL_WM_SetCaption(g_winTitle, NULL); // TODO: insert icon in place of NULL
	
	// Set GL options
	glEnable(GL_TEXTURE_2D);
	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glShadeModel(GL_SMOOTH);
	glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
	
	// Setup GL view matrices
	glViewport(0, 0, g_winWidth, g_winHeight);
	
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(0, g_winWidth, g_winHeight, 0, -0.1f, 0.0f);
	
	glMatrixMode(GL_MODELVIEW);	/* Default matrix mode is GL_MODELVIEW */
	glLoadIdentity();
}

/*
 * Shutdown subsystems and free all used memory
 */
void CleanUp()
{	
	SDL_FreeSurface(g_windowSurface);
	
	animTest->freeLists();
	animTest->getTexture().freeTexture();
	
	SDL_Quit();
}

/*
 * Attempts to switch between windowed and fullscreen
 * Returns false if unsuccessful
 */
bool ToggleFullScreen()
{
	SDL_FreeSurface(g_windowSurface);
	
	if((g_winFlags & SDL_FULLSCREEN) > 0)
		g_winFlags ^= SDL_FULLSCREEN;
	else
		g_winFlags |= SDL_FULLSCREEN;
	
	g_windowSurface = SDL_SetVideoMode(g_winWidth, g_winHeight, g_winBpp, g_winFlags);
	
	if(!g_windowSurface)
	{
		fprintf(stderr, "Couldn't set video mode: %s\n", SDL_GetError());
		return false;
	}
	else
		return true;
}

/*
 * Update events
 */
void Update()
{
	SDL_Event event;
	while(SDL_PollEvent(&event))
	{
		switch(event.type)
		{
		case SDL_QUIT:
			g_running = false;
			break;
			
		case SDL_KEYDOWN:
			switch(event.key.keysym.sym)
			{
			case SDLK_F11:
				if(!ToggleFullScreen())
					g_running = false;
				break;
				
			case SDLK_F12:
				g_running = false;
				break;
			}
			break;
		}
		/* Pass events to event handlers here */
	}
	Render();
}

/*
 * Draw scene
 */
void Render()
{
	glClear(GL_COLOR_BUFFER_BIT);
	
	/* All Drawing goes here- starting in GL_MODELVIEW mode */
	glLoadIdentity();
	animTest->draw(0,0);
	
	SDL_GL_SwapBuffers();
}

/*
 * Entry Point
 */
int main(char* argc, char** argv)
{
	InitFileSystem(argv[0], ".birdtoast", "..");
	
	InitVideo();
	
	// Load test xml file
	animTest = new Animation();
	animTest->loadFromXMLFile("data/anim_test.bt");
	animTest->start();
	
	InitMainLoop(&Update, g_running);
	
	CleanUp();
	
	DeinitFileSystem();
	
	return 0;
}
